"""
AI自动开发 - 项目管理服务层
负责项目初始化、信息管理、开发日志管理、工作流控制
"""

import os
import sys
import subprocess
import venv
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Any
import json

# 导入工具函数
from utils import format_timestamp, handle_errors, normalize_path, get_file_info


class ProjectService:
    """项目管理服务类"""

    def __init__(self):
        self.project_info_file = "PROJECT_INFO.md"
        self.dev_log_file = "DEVELOPMENT_LOG.md"
        self.venv_dir = "venv"
        self.requirements_file = "requirements.txt"

    def is_project_initialized(self, project_path: str) -> bool:
        """检查指定路径是否已经是一个项目"""
        project_dir = Path(project_path)
        if not project_dir.exists():
            return False

        # 检查项目标识文件是否存在
        project_info_path = project_dir / self.project_info_file
        venv_path = project_dir / self.venv_dir

        return project_info_path.exists() and venv_path.exists()

    @handle_errors(default_return=False)
    def create_project_directory(self, project_path: str) -> bool:
        """创建项目目录"""
        Path(project_path).mkdir(parents=True, exist_ok=True)
        return True

    def create_virtual_environment(self, project_path: str) -> Dict[str, Any]:
        """在项目目录中创建虚拟环境"""
        try:
            project_dir = Path(project_path)
            venv_path = project_dir / self.venv_dir

            # 如果虚拟环境已存在，跳过创建
            if venv_path.exists():
                return {
                    'success': True,
                    'message': f'虚拟环境已存在: {venv_path}',
                    'venv_path': str(venv_path)
                }

            # 创建虚拟环境
            venv.create(venv_path, with_pip=True)

            # 验证虚拟环境创建成功
            if venv_path.exists():
                return {
                    'success': True,
                    'message': f'虚拟环境创建成功: {venv_path}',
                    'venv_path': str(venv_path)
                }
            else:
                return {
                    'success': False,
                    'message': '虚拟环境创建失败: 目录未生成'
                }

        except Exception as e:
            return {
                'success': False,
                'message': f'虚拟环境创建失败: {str(e)}'
            }

    def create_project_info(self, project_path: str, name: str, description: str, template_type: str = "basic") -> bool:
        """创建项目信息文件"""
        try:
            project_dir = Path(project_path)
            info_file_path = project_dir / self.project_info_file

            # 基础项目信息模板
            project_info_content = f"""# {name}

## 项目描述
{description}

## 项目信息
- **项目名称**: {name}
- **项目类型**: {template_type}
- **创建时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- **Python版本**: {sys.version.split()[0]}
- **虚拟环境**: ./venv/

## 项目结构
```
{name}/
├── venv/                 # 虚拟环境
├── src/                  # 源代码目录
├── tests/                # 测试代码目录
├── requirements.txt      # 依赖包列表
├── PROJECT_INFO.md       # 项目信息（本文件）
└── DEVELOPMENT_LOG.md    # 开发日志
```

## 开发阶段
- **当前阶段**: 需求沟通
- **完成阶段**: 无
- **下一阶段**: 需求沟通 → 架构设计

## 功能模块
待定义...

## 技术栈
- **编程语言**: Python {sys.version.split()[0]}
- **开发环境**: 虚拟环境
- **依赖管理**: pip + requirements.txt

## 使用方法
项目初始化完成，等待需求确认和功能设计。

## 开发进度
- [x] 项目初始化
- [ ] 需求分析和确认
- [ ] 架构设计
- [ ] 功能实现
- [ ] 测试和集成

## 注意事项
- 所有Python命令将在虚拟环境中执行
- 请通过修改本文件来更新项目信息
- 开发过程中的重要决策和变更请记录到开发日志中
"""

            info_file_path.write_text(project_info_content, encoding='utf-8')
            return True

        except Exception as e:
            print(f"创建项目信息文件失败: {e}")
            return False

    def create_development_log(self, project_path: str) -> bool:
        """创建开发日志文件"""
        try:
            project_dir = Path(project_path)
            log_file_path = project_dir / self.dev_log_file

            log_content = f"""# 开发日志

## 项目初始化
**时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}  
**操作**: 项目创建  
**详情**: 
- 创建项目目录结构
- 初始化虚拟环境
- 生成项目信息文件
- 创建开发日志文件

**状态**: ✅ 完成

---

## 文件操作日志

"""

            log_file_path.write_text(log_content, encoding='utf-8')
            return True

        except Exception as e:
            print(f"创建开发日志文件失败: {e}")
            return False

    def create_requirements_file(self, project_path: str, template_type: str = "basic") -> bool:
        """创建requirements.txt文件"""
        try:
            project_dir = Path(project_path)
            requirements_path = project_dir / self.requirements_file

            # 根据模板类型设置基础依赖
            base_requirements = {
                'basic': [],
                'web_app': ['Flask>=2.3.0', 'Flask-SQLAlchemy>=3.0.0'],
                'cli_tool': ['click>=8.1.0', 'colorama>=0.4.6'],
                'data_analysis': ['pandas>=2.0.0', 'numpy>=1.24.0', 'matplotlib>=3.7.0']
            }

            requirements = base_requirements.get(template_type, [])
            content = '\n'.join(requirements) + '\n' if requirements else '# 项目依赖包列表\n# 使用 pip install -r requirements.txt 安装\n'

            requirements_path.write_text(content, encoding='utf-8')
            return True

        except Exception as e:
            print(f"创建requirements.txt失败: {e}")
            return False

    def create_basic_structure(self, project_path: str) -> bool:
        """创建基础目录结构"""
        try:
            project_dir = Path(project_path)

            # 创建基础目录
            directories = ['src', 'tests']
            for dir_name in directories:
                dir_path = project_dir / dir_name
                dir_path.mkdir(exist_ok=True)

                # 创建__init__.py文件（Python包标识）
                init_file = dir_path / '__init__.py'
                if not init_file.exists():
                    init_file.write_text('# Python包标识文件\n', encoding='utf-8')

            return True

        except Exception as e:
            print(f"创建基础目录结构失败: {e}")
            return False

    def log_file_change(self, project_path: str, filepath: str, operation: str, summary: str = "") -> bool:
        """记录文件变更到开发日志（自动调用）"""
        try:
            project_dir = Path(project_path)
            log_file_path = project_dir / self.dev_log_file

            if not log_file_path.exists():
                return False

            timestamp = format_timestamp()
            log_entry = f"[{timestamp}] {operation.upper()} {filepath}"

            if summary.strip():
                log_entry += f" - {summary.strip()}"

            log_entry += "\n"

            # 追加到日志文件
            with open(log_file_path, 'a', encoding='utf-8') as f:
                f.write(log_entry)

            return True

        except Exception as e:
            print(f"记录文件变更日志失败: {e}")
            return False

    def log_stage_summary(self, project_path: str, stage: str, summary: str) -> bool:
        """记录阶段总结到开发日志（LLM主动调用）"""
        try:
            project_dir = Path(project_path)
            log_file_path = project_dir / self.dev_log_file

            if not log_file_path.exists():
                return False

            timestamp = format_timestamp()

            log_entry = f"\n---\n\n## {stage}阶段总结\n"
            log_entry += f"**时间**: {timestamp}\n"
            log_entry += f"**总结**: {summary}\n\n"

            # 追加到日志文件
            with open(log_file_path, 'a', encoding='utf-8') as f:
                f.write(log_entry)

            return True

        except Exception as e:
            print(f"记录阶段总结失败: {e}")
            return False

    def update_project_info(self, project_path: str, new_content: str) -> Dict[str, Any]:
        """更新项目信息文件内容"""
        try:
            project_dir = Path(project_path)
            info_file_path = project_dir / self.project_info_file

            if not info_file_path.exists():
                return {
                    'success': False,
                    'message': '项目信息文件不存在'
                }

            # 备份原文件
            backup_content = info_file_path.read_text(encoding='utf-8')

            # 写入新内容
            info_file_path.write_text(new_content, encoding='utf-8')

            # 记录到开发日志
            self.log_file_change(project_path, self.project_info_file, 'EDIT', '更新项目信息')

            return {
                'success': True,
                'message': '项目信息更新成功',
                'file_path': str(info_file_path),
                'backup_content': backup_content
            }

        except Exception as e:
            return {
                'success': False,
                'message': f'更新项目信息失败: {str(e)}'
            }

    def get_project_info(self, project_path: str) -> Dict[str, Any]:
        """获取项目信息"""
        try:
            project_dir = Path(project_path)
            info_file_path = project_dir / self.project_info_file

            if not info_file_path.exists():
                return {
                    'success': False,
                    'message': '项目信息文件不存在'
                }

            content = info_file_path.read_text(encoding='utf-8')

            return {
                'success': True,
                'content': content,
                'file_path': str(info_file_path),
                'last_modified': datetime.fromtimestamp(info_file_path.stat().st_mtime).strftime('%Y-%m-%d %H:%M:%S')
            }

        except Exception as e:
            return {
                'success': False,
                'message': f'获取项目信息失败: {str(e)}'
            }

    def get_project_status(self, project_path: str) -> Dict[str, Any]:
        """获取项目状态概览"""
        try:
            project_dir = Path(project_path)

            if not self.is_project_initialized(project_path):
                return {
                    'success': False,
                    'message': '项目未初始化'
                }

            # 统计基本信息
            files_count = len([f for f in project_dir.rglob('*') if f.is_file() and not str(f).startswith(str(project_dir / self.venv_dir))])

            # 获取最后修改时间
            info_file = project_dir / self.project_info_file
            last_modified = datetime.fromtimestamp(info_file.stat().st_mtime).strftime('%Y-%m-%d %H:%M:%S')

            # 检查虚拟环境状态
            venv_path = project_dir / self.venv_dir
            venv_status = "✅ 正常" if venv_path.exists() else "❌ 缺失"

            return {
                'success': True,
                'project_path': str(project_dir.absolute()),
                'files_count': files_count,
                'last_modified': last_modified,
                'venv_status': venv_status,
                'venv_path': str(venv_path),
                'info_file': str(info_file),
                'log_file': str(project_dir / self.dev_log_file)
            }

        except Exception as e:
            return {
                'success': False,
                'message': f'获取项目状态失败: {str(e)}'
            }

    def init_project(self, project_path: str, name: str, description: str, template_type: str = "basic") -> Dict[str, Any]:
        """初始化项目（主要方法）"""
        try:
            # 转换为绝对路径
            project_path = str(Path(project_path).resolve())

            # 检查是否已经是项目
            if self.is_project_initialized(project_path):
                return {
                    'success': False,
                    'message': f'项目已存在，无需重复初始化',
                    'project_path': project_path
                }

            # 步骤1: 创建项目目录
            if not self.create_project_directory(project_path):
                return {
                    'success': False,
                    'message': '创建项目目录失败'
                }

            # 步骤2: 创建虚拟环境
            venv_result = self.create_virtual_environment(project_path)
            if not venv_result['success']:
                return {
                    'success': False,
                    'message': f"虚拟环境创建失败: {venv_result['message']}"
                }

            # 步骤3: 创建基础目录结构
            if not self.create_basic_structure(project_path):
                return {
                    'success': False,
                    'message': '创建基础目录结构失败'
                }

            # 步骤4: 创建requirements.txt
            if not self.create_requirements_file(project_path, template_type):
                return {
                    'success': False,
                    'message': '创建requirements.txt失败'
                }

            # 步骤5: 创建项目信息文件
            if not self.create_project_info(project_path, name, description, template_type):
                return {
                    'success': False,
                    'message': '创建项目信息文件失败'
                }

            # 步骤6: 创建开发日志
            if not self.create_development_log(project_path):
                return {
                    'success': False,
                    'message': '创建开发日志失败'
                }

            # 成功创建
            return {
                'success': True,
                'message': f'项目 "{name}" 初始化成功',
                'project_path': project_path,
                'template_type': template_type,
                'venv_path': venv_result['venv_path'],
                'next_stage': 'requirement_communication',
                'files_created': [
                    self.project_info_file,
                    self.dev_log_file,
                    self.requirements_file,
                    'src/__init__.py',
                    'tests/__init__.py'
                ]
            }

        except Exception as e:
            return {
                'success': False,
                'message': f'项目初始化失败: {str(e)}'
            }


# 全局实例
project_service = ProjectService()


# 测试代码
if __name__ == "__main__":
    # 测试项目初始化
    test_path = "./test_project"
    result = project_service.init_project(
        project_path=test_path,
        name="测试项目",
        description="这是一个用于测试项目管理功能的测试项目",
        template_type="basic"
    )

    print("项目初始化结果:")
    print(json.dumps(result, indent=2, ensure_ascii=False))

    if result['success']:
        print("\n项目状态:")
        status = project_service.get_project_status(test_path)
        print(json.dumps(status, indent=2, ensure_ascii=False))

        print("\n项目信息:")
        info = project_service.get_project_info(test_path)
        if info['success']:
            print(info['content'])